#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <iostream>


using std::cout;
using std::endl;

//子线程执行流的入口
//子线程本质上就是一个函数
//子线程要做的任务是：每一秒产生1个随机数，一共产生10个
void * start_routine(void * arg)
{
    cout << "sub thread is running." << endl;
    int cnt = 10;//存储线程自己的栈空间
    srand(time(NULL));
    while(cnt-->0) {
        int num = rand() % 100;
        cout << "thid " << pthread_self() << ", num:" << num << endl;
        sleep(1);
    }

    //pthread_exit(NULL);
    return (void*)1;
}


int main()
{
    pthread_t pthid;
    int ret = pthread_create(&pthid, NULL, start_routine, NULL);
    if(ret != 0) {
        fprintf(stderr, "pthread_create:%s\n", strerror(ret));
        return EXIT_FAILURE;
    }

    cout << "main thread is running, sub thread id:" << pthid << endl;

    int * p = nullptr;
    pthread_join(pthid, (void**)&p);
    cout << "p:" << p << endl;
    return 0;
}

